from fastapi import APIRouter, HTTPException, Depends
from api.package_material.storage import (
    StorageRecord,
    get_storage_records,
    add_storage_record,
    get_material_list
)
from typing import Optional, List

from util.JWT import get_current_user

router = APIRouter(
    prefix="/package-material/storage",
    tags=["package-material"]
)

@router.get("/list")
async def get_storage_list(
    search: str = '',
    storage_type: Optional[str] = None,  # 'I' for in, 'O' for out
    start_date: Optional[str] = None,
    end_date: Optional[str] = None,
    page: int = 1,
    page_size: int = 10,
    id: dict = Depends(get_current_user)
):
    result = get_storage_records(search, storage_type, start_date, end_date, page, page_size)
    if result is None:
        raise HTTPException(status_code=500, detail="获取记录失败")
    return {
        "code": 200,
        "data": {
            "code": 200,
            "records": result["records"],
            "total": result["total"]
        }
    }

@router.post("/add")
async def create_storage_record(storage: StorageRecord, id: dict = Depends(get_current_user)):
    result = add_storage_record(storage)
    if result is None:
        error_message = "操作失败，请检查包材编码是否存在"
        if storage.storage_type == 'O':
            error_message += "或库存是否充足"
        raise HTTPException(status_code=500, detail=error_message)
    return {"code": 200, "message": "操作成功"}

@router.get("/materials")
async def get_materials(id: dict = Depends(get_current_user)):
    try:
        result = get_material_list()
        if result is None:
            raise HTTPException(
                status_code=500, 
                detail="获取包材列表失败，请检查服务器日志"
            )
        return {"code": 200, "data": result}
    except Exception as e:
        print(f"Error in get_materials endpoint: {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"获取包材列表时发生错误: {str(e)}"
        ) 